import { defineStore } from "pinia"
import { ref, computed } from "vue"
import cache from "@/utils/cache"
import { getUserInfo } from "@/api/user"

const useUserStore = defineStore(
    "user",
    () => {
        const userInfo = ref({})
        const token = ref(cache.get("token") || null)
        const temToken = ref(null)

        const isLogin = computed(() => !!token.value)

        const getUser = async () => {
            const data = await getUserInfo({
                token: token.value || temToken.value
            })
            userInfo.value = data
            return data
        }

        const login = (res) => {
            token.value = res
            cache.set("token", res)
        }

        const logout = () => {
            cache.remove("token")
            token.value = ""
            userInfo.value = {}
        }

        return {
            userInfo,
            token,
            temToken,
            isLogin,
            getUser,
            login,
            logout
        }
    },
    {
        persist: true
    }
)

export default useUserStore
